package com.wk.springboot.parse;

import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class SpELParser {
    private final ExpressionParser parser = new SpelExpressionParser();
    private final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    /**
     * 解析SpEL表达式
     * @param spEL 表达式字符串
     * @param method 目标方法
     * @param args 方法参数
     * @return 解析结果
     */
    public String parseSpEL(String spEL, Method method, Object[] args) throws Exception {
        try {
            EvaluationContext context = createEvaluationContext(method, args);
            Expression expression = parser.parseExpression(spEL);
            return expression.getValue(context, String.class);
        } catch (Exception e) {
            throw new Exception("SpEL解析失败: " + spEL, e);
        }
    }

    /**
     * 构建SpEL上下文
     */
    private EvaluationContext createEvaluationContext(Method method, Object[] args) {
        String[] paramNames = parameterNameDiscoverer.getParameterNames(method);
        if (paramNames == null) {
            return new StandardEvaluationContext();
        }

        StandardEvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(paramNames[i], args[i]);
        }
        return context;
    }
}